package com.asurplus.api.controller;

import com.asurplus.common.minio.MinioUtils;
import com.asurplus.common.utils.BASE64DecodedMultipartFile;
import com.asurplus.common.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "文件相关")
@RestController
@RequestMapping("/api/upload")
public class UploadApiController {

    @Autowired
    private MinioUtils minioUtils;

    @ApiOperation(value = "上传文件", notes = "上传文件")
    @PostMapping(value = "upload", headers = "content-type=multipart/form-data")
    public ResponseResult upload(HttpServletRequest request) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        return minioUtils.uploadFile(multiRequest.getFile("file"), "app");
    }

    @ApiOperation(value = "BASE64上传文件", notes = "BASE64上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "base", value = "BASE64内容")
    })
    @PostMapping("uploadBase")
    public ResponseResult uploadBase(String base) {
        if (StringUtils.isBlank(base)) {
            return ResponseResult.error("上传失败");
        }
        return minioUtils.uploadFile(BASE64DecodedMultipartFile.base64ToMultipart(base), "app");
    }
}
